﻿using System;
using System.Collections.Generic;
using System.Linq;
using Sharp.DataTransferObject.CMS;
using Sharp.Domain.CMSBoundedContext.AritcleModule.Aggregates;
using Sharp.Domain.CMSBoundedContext.AritcleModule.GatherEngine;
using Sharp.Infrastructure;
using Sharp.Infrastructure.Crosscutting;
using Sharp.Infrastructure.Search;

namespace Sharp.Application.CMS
{
    public partial class CMSServiceImpl
    {
        #region Gather

        [Logging("删除采集规则，Id：{@p0}")]
        public Result DeleteGathers(Guid[] ids)
        {
            var res = new Result();
            if (ids == null)
            {
                res.Err = "参数不可为空。";
                return res;
            }

            _gatherRepository.Remove(ids);

            Context.Commit();

            return res;
        }
        [Logging("保存采集规则，{@p0.Name}")]
        public Result SaveGather(GatherDTO dtoModel)
        {
            Result res = new Result();
            string[] textArray1 = dtoModel.Filter?.Split('\n');
            string[] textArray2 = dtoModel.Replace?.Split('\n');

            if (textArray2 != null && textArray1 != null && (textArray1.Length != textArray2.Length))
            {
                res.Err = "“过滤内容”和被“被替换为”的行数要一致\\n“过滤内容”为" + textArray1.Length + "行\\n“被替换为”也应该为" + textArray1.Length +
                          "行";
            }
            else
            {
                if (dtoModel.Id.IsEmpty())
                {
                    Gather gather = dtoModel.To<Gather>();
                    _gatherRepository.Add(gather);
                    res.LogMessage = "添加文章采集规则" + gather.Name;
                }
                else
                {
                    var persisted = _gatherRepository.Get(dtoModel.Id);
                    persisted.Author = dtoModel.Author;
                    persisted.CanDownImg = dtoModel.CanDownImg;
                    persisted.CanDrawWaterMark = dtoModel.CanDrawWaterMark;
                    persisted.CategoryArea = dtoModel.CategoryArea;
                    persisted.CategoryPageNextUrl = dtoModel.CategoryPageNextUrl;
                    persisted.ComeFrom = dtoModel.ComeFrom;
                    persisted.Content = dtoModel.Content;
                    persisted.ContentPageNextUrl = dtoModel.ContentPageNextUrl;
                    persisted.ContentPageUrl = dtoModel.ContentPageUrl;
                    persisted.ContentTitle = dtoModel.ContentTitle;
                    persisted.Encoding = dtoModel.Encoding;
                    persisted.Filter = persisted.Filter;
                    persisted.FullArticleUrl = dtoModel.FullArticleUrl;
                    persisted.IgnoreUrl = dtoModel.IgnoreUrl;
                    persisted.IsDisabled = dtoModel.IsDisabled;
                    persisted.IsExpert = dtoModel.IsExpert;
                    persisted.Name = dtoModel.Name;
                    persisted.Replace = dtoModel.Replace;
                    persisted.StartUrl = dtoModel.StartUrl;
                    persisted.UpdateTime = dtoModel.UpdateTime;
                    persisted.ContentPageRule = dtoModel.ContentPageRule;
                    persisted.SpiderDomains = dtoModel.SpiderDomains;
                    persisted.IsSpider = dtoModel.IsSpider;

                    _gatherRepository.Update(persisted);
                    res.LogMessage = "修改文章采集规则" + persisted.Id;
                }
            }

            _gatherRepository.Context.Commit();
            return res;
        }

        public Result<GatherDTO> GetGatherInfo(Guid id)
        {
            var res = new Result<GatherDTO>();
            res.Data = _gatherRepository.Get(id).To<GatherDTO>();
            return res;
        }

        public PagedResult<GatherDTO> GetGatherPaged(PagingFeature pf)
        {
            var paged = _gatherRepository.Pagging(pf, x => x.ParentId == null, "CheckInTime DESC", "Children").To<Gather, GatherDTO>();

            paged.Data.ToList().ForEach(x =>
            {
                x.ArticleGatherCount = _articleRepository.Count(a => a.GatherId == x.Id);
            });

            return paged;
        }

        #endregion

        /// <summary>
        /// 采集栏目页面
        /// </summary>
        /// <param name="cp"></param>
        /// <returns></returns>
        public ClassGatherResultDTO GatherCategoryPage(CategoryParameterDTO cp)
        {
            var res = _gatherEngineMain.GatherCategoryPage(cp.To<CategoryParameter>());
            return res.To<ClassGatherResultDTO>();
        }

        /// <summary>
        ///     采集内容页
        /// </summary>
        /// <param name="wp"></param>
        /// <returns></returns>
        public ContentPageGatherResultDTO GatherPage(WebParameterDTO wp)
        {
            _gatherContentPage.Init(wp.To<WebParameter>());

            return _gatherContentPage.GatherPage(wp.Urls).To<ContentPageGatherResultDTO>();
        }

        public Result<IList<GatherDTO>> GetGathers()
        {
            var res = new Result<IList<GatherDTO>>();

            res.Data = _gatherRepository.GetList(x => x.ParentId == null).To<List<GatherDTO>>();

            res.Data.ToList().ForEach(x =>
            {
                x.ArticleGatherCount = _articleRepository.Count(a => a.GatherId == x.Id);
            });

            return res;
        }

        /// <summary>
        /// 拆解网页
        /// </summary>
        /// <returns></returns>
        public ContentPageGatherResultDTO DecomposePage(string strUrl, Guid gatherId, string webhtml)
        {
            _gatherContentPage.Init(gatherId);
            return _gatherContentPage.DecomposePage(strUrl, false, webhtml).To<ContentPageGatherResultDTO>();
        }
    }
}